import { defineStore } from 'pinia';
import taskApi from '../api/task';

export const useTaskStore = defineStore('task', {
  state: () => ({
    tasks: [],
    currentListId: null,
    loading: false,
    error: null
  }),

  getters: {
    getTasks: (state) => state.tasks,
    getTasksByStatus: (state) => (status) => {
      return state.tasks.filter(task => task.status === status);
    }
  },

  actions: {
    // 设置当前列表ID
    setCurrentListId(listId) {
      this.currentListId = listId;
    },

    // 获取任务列表
    async fetchTasks(listId) {
      this.loading = true;
      this.error = null;
      try {
        const response = await taskApi.getTasks(listId);
        this.tasks = response;
        this.currentListId = listId;
      } catch (error) {
        this.error = error.message || '获取任务失败';
        console.error('获取任务失败:', error);
      } finally {
        this.loading = false;
      }
    },

    // 添加任务
    async createTask(taskData) {
      this.loading = true;
      this.error = null;
      try {
        const response = await taskApi.createTask(this.currentListId, taskData);
        // 添加到本地状态
        this.tasks.push(response);
        return response;
      } catch (error) {
        this.error = error.message || '添加任务失败';
        console.error('添加任务失败:', error);
        throw error;
      } finally {
        this.loading = false;
      }
    },

    // 更新任务
    async updateTask(taskData) {
      this.loading = true;
      this.error = null;
      try {
        const response = await taskApi.updateTask(taskData.id, taskData);
        // 更新本地状态
        const index = this.tasks.findIndex(task => task.id === taskData.id);
        if (index !== -1) {
          this.tasks[index] = { ...this.tasks[index], ...response };
        }
        return response;
      } catch (error) {
        this.error = error.message || '更新任务失败';
        console.error('更新任务失败:', error);
        throw error;
      } finally {
        this.loading = false;
      }
    },

    // 删除任务
    async removeTask(id) {
      this.loading = true;
      this.error = null;
      try {
        await taskApi.deleteTask(id);
        // 更新本地状态
        this.tasks = this.tasks.filter(task => task.id !== id);
      } catch (error) {
        this.error = error.message || '删除任务失败';
        console.error('删除任务失败:', error);
        throw error;
      } finally {
        this.loading = false;
      }
    },

    // 完成/取消完成任务
    async toggleTaskStatus(id, status) {
      this.loading = true;
      this.error = null;
      try {
        await taskApi.toggleTaskStatus(id, status);
        // 更新本地状态
        const index = this.tasks.findIndex(task => task.id === id);
        if (index !== -1) {
          this.tasks[index].status = status;
        }
      } catch (error) {
        this.error = error.message || '更新任务状态失败';
        console.error('更新任务状态失败:', error);
        throw error;
      } finally {
        this.loading = false;
      }
    }
  }
});
